// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import {saveCookie, getUrlParam, getCookie} from "./service/util.service";
import {getNetworkType} from "./service/util.function";

// jquery
import $ from 'jquery';

window.$ = $;

// 引入vux配置组件
import './config/vux.config'

// axios
import axios from './config/axios.config'

// vuex
import store from './store'

// 配置NProgress 全站进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.inc(0.2);
NProgress.configure({easing: 'ease', speed: 500, showSpinner: false});

// 公共样式
import './assets/styles/common.scss'
// 阻止启动生产消息
Vue.config.productionTip = false;

import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)
// 动态改变页面title
Vue.directive('title', (el, binding) => {
  if (binding.value !== undefined) {
    document.title = `${binding.value}`;
  }
});

// 获取嵌入APP信息
router.UA = (() => {
  let u = navigator.userAgent;
  let u2 = navigator.userAgent.toLowerCase();
  return { //移动终端浏览器版本信息
    trident: u.indexOf('Trident') > -1, //IE内核
    presto: u.indexOf('Presto') > -1, //opera内核
    webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, //火狐内核
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
    android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
    iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
    iPad: u.indexOf('iPad') > -1, //是否iPad
    webApp: u.indexOf('Safari') === -1, //是否web应该程序，没有头部与底部
    iosv: u.substr(u.indexOf('iPhone OS') + 9, 3),
    weixin: u2.match(/MicroMessenger/i) ? u2.match(/MicroMessenger/i).toString() === "micromessenger" : false,
    qq: u2.match(/QQ\//i) ? u2.match(/QQ\//i).toString() === "qq/" : false,
    APP: u2.match(/newLoanMarket/i) ? u2.match(/newLoanMarket/i).toString() === "newloanmarket" : false,
    ali: u.indexOf('AliApp') > -1,
    system_name: u2.indexOf('windows') > -1 ? '1' : (u2.indexOf('android') > -1 ? '3' : (u2.indexOf('macintosh') > -1 ? '4' : (u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) ? '2' : ''))),
    system_version: '',
    equ_model: '',
    package: u.match(/(com.[a-z.]*)(?=\/)/g) ? u.match(/(com.[a-z.]*)(?=\/)/g).toString() : 'com.default.app',
    networkType: getNetworkType()
  };
});

router.back = function (query = {}) {
  if (query.redirectUrl) {
    return window.location.href = query.redirectUrl;
  } else if (window.history.length <= 2) {
    return router.replace({path: '/'});
  } else {
    router.go(-1);
  }
};

// 百度统计 必须把_hmt挂载到window下，否则找不到
let _hmt = [];
_hmt = _hmt || []
window._hmt = _hmt;
window.returnCitySN = {cip: 0};
// window.returnCitySN2 = {};
(function () {
  let s = document.getElementsByTagName("script")[0];
  /* let hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?ebe630fb4e5f3942bacf0f2a152e938c";
  s.parentNode.insertBefore(hm, s); */

  // city地址 err需要
  let hm2 = document.createElement("script");
  hm2.src = "https://pv.sohu.com/cityjson?ie=utf-8";
  s.parentNode.insertBefore(hm2, s);
  // city地址 err需要
  /* let ttt = setInterval(() => {
    if(window.returnCitySN.cip != 0){
      getIp()
      clearInterval(ttt)
    }
  }, 100);
  function getIp(){
    $.ajax({
      url:`//restapi.amap.com/v3/ip?parameters&key=6517bfa94cea3b27dd3cd8aa1ed7cebe&type=ipv4&ip=${window.returnCitySN.cip}`,
      dataType:'jsonp',
      processData: false, 
      type:'get',
      success:function(data){
        window.returnCitySN2 = data
      }
    })
  } */
})();

let remInit = function () {
  (function () {
    let rem, dpr, time, doc = window.document,
      docEl = doc.documentElement,
      viewport = doc.querySelector('meta[name="viewport"]'),
      zoomScale,
      zoomScaleNum;
    if (viewport) {
      zoomScale = viewport.getAttribute("content").match(/initial\-scale=(["']?)([\d\.]+)\1?/);
      if (zoomScale) {
        zoomScaleNum = parseFloat(zoomScale[2]);
        dpr = parseInt(1 / zoomScaleNum);
      }
    }
    if (!dpr && !zoomScaleNum) {
      let os = (window.navigator.appVersion.match(/android/gi), window.navigator.appVersion.match(/iphone/gi));
      dpr = window.devicePixelRatio;
      dpr = os ? dpr >= 3 ? 3 : dpr >= 2 ? 2 : 1 : 1;
      zoomScaleNum = 1 / dpr;
    }
    
    //改变基准rem
    function changeRem() {
      let docWidth = docEl.getBoundingClientRect().width;
      if (docWidth / dpr > 750) {
        docWidth = 750 * dpr;
      }
      //rem字号以320下的16px为基线进行等比缩放
      rem = docWidth / 320 * 16;
      docEl.style.fontSize = rem + "px";
    }
    window.addEventListener("resize", function () {
      clearTimeout(time);
      time = setTimeout(changeRem, 100);
    }, false);


    changeRem();
  })();
};

router.beforeEach(({meta, path, name, params, query, fullPath}, from, next) => {
  remInit()
  // 获取设置 guide 正则防止三方添加异常参数
  let channel = query.id || getUrlParam('guide') || getCookie('guide') || '';
  let match = channel.match(/([0-9]*)/i);
  if (match && match[0]) {
    saveCookie('guide', match[0]);
  } else {
    saveCookie('guide', 0);
  }
  NProgress.start();
  next();
});

router.afterEach((to, from) => {
  NProgress.done(true);
});

Object.defineProperty(Vue.prototype, '$http', {value: axios});

// eslint-disable no-new
new Vue({
  el: '#app',
  store,
  router,
  components: {App},
  template: '<App/>'
});
